<template>
  <div class="form_box">
    <el-form :model="dataForm" :rules="dataFormRules" ref="dataForm" label-width="100px" class="demo-ruleForm">
      <!-- k -->
      <el-form-item label="k" prop="k">
        <el-input v-model="dataForm.k"></el-input>
      </el-form-item>

      <!-- n -->
      <el-form-item label="name" prop="name">
        <el-input v-model="dataForm.name"></el-input>
      </el-form-item>

      <!-- 确认 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm()" :loading="loading">立即更新</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'

import {demoEditInitApi,demoEditSaveApi} from '@/manager-core/api/demo/demo'



export default defineComponent({
  name: 'DemoEdit',

  components: {
    
  },

  data(){
    return {      
      dataForm: {
        id: '' as any,
        k: '',
        name: ''
      },
      dataFormRules: {
        k: [
          {required:true,message: '请输入k',trigger: 'blur'}
        ],
        name: [
          {required:true,message: '请输入name',trigger: 'blur'}
        ]
      },
      loading : false      
    }
  },

  methods:{
    init(){
      if(this.loading){
        return
      }

      this.loading = true;

      demoEditInitApi(this.dataForm.id)
        .then((r:any)=>{
          this.dataForm.k = r.k;
          this.dataForm.name = r.name;
        })
        .finally(()=>{
            this.loading = false;
        })
      
    },

    submitForm(){

      (this.$refs['dataForm'] as any)
      .validate((valid:any)=>{
        if(valid){
          // 验证通过
          console.log("submitForm success")

          this.loading = true;

          demoEditSaveApi(this.dataForm)
            .then(()=>{
                ElMessage.success("更新成功！");
            })
            .finally(()=>{
              this.loading = false;              
            })


        }
        else{
          // 未验证通过
          ElMessage.error("未通过表单验证，请检查表单项");
        }
      })
    }
  },

  mounted(){
    let id = this.$route.query.id;
    if(!id){
      alert("页面错误，请刷新")
    }
    else {
      this.dataForm.id = id;
      this.init();
    }
  },

  created(){
    
  },

  setup(){
    // const store = useStore()

    // return {
    //   LoginByUsername:(userObj:any)=> store.dispatch('LoginByUsername')
    // }

  }


})



</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
</style>
